﻿using System;
using System.Collections.Generic;
using Jlvier.TaobaoShowcase.Service;
using Taobao.ObjectModel.Request;

namespace ShowWindowIntelligence
{
    internal class WillDelist : IShowWindowRule 
    {
        private readonly List<Product> requirement;
        private readonly List<Product> exclusion;
        private static int showCaseCount;

        private delegate void RecommedationHandler(object productItem);
 
        public WillDelist(List<Product> requirement, List<Product> exclusion)
        {
            if (null == requirement) throw new ArgumentNullException("requirement");
            if (null == exclusion) throw new ArgumentNullException("exclusion");
            this.requirement = requirement;
            this.exclusion = exclusion;
            
        }

        public List<Product> Requirement
        {
            get { return requirement;}
        }

        public List<Product> Exclusion
        {
            get { return exclusion; }
        }

        public string RuleName
        {
            get { throw new NotImplementedException(); }
        }

        public void Apply()
        {
            var productItemService = ServiceProvider.Instance.GetService<IProductItemService>();

            var removeRequest = RequestFactory.CreateItemsOnsaleRequest(RequestOption.Default, true);
            RemoveRecommendation(new ProductItemsRetriever(removeRequest), productItemService.RemoveRecommendation);

            showCaseCount = Shop.GetShowcaseCount();
            var addRequest = RequestFactory.CreateItemsOnsaleRequest(RequestOption.Default, false);
            Recommend(new ProductItemsRetriever(addRequest, RecommendationCompleted), productItemService.Recommend);
        }


        private void RemoveRecommendation(ProductItemsRetriever retriever, RecommedationHandler handler)
        {
            retriever.OnProductsRetrieved += ((sender, args) => handler(args.ProductItem));
            retriever.Fetch();
        }
        private void Recommend(ProductItemsRetriever retriever, RecommedationHandler handler)
        {
            int recommendationCount = 0;
            retriever.OnProductsRetrieved += delegate(object sender, ProductsRetrievedEventArgs args)
            {
                if (recommendationCount == showCaseCount) return;
                handler(args.ProductItem);
                recommendationCount++;
            };
            retriever.Fetch();
        }
        
        private static bool RecommendationCompleted(Response response)
        {
            return ( response.Count>=showCaseCount);
        }
    }
}